/*
 * @lc app=leetcode.cn id=530 lang=typescript
 *
 * [530] 二叉搜索树的最小绝对差
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

// 转中序数组排序，排序后找两个相邻之间的差值即可

function getMinimumDifference(root: TreeNode | null): number {
    const a = rebuild(root);
    let diff = Infinity;
    let i = 0;
    let j = 1;
    while (j < a.length) {
        const newDiff = a[j] - a[i];
        diff = Math.min(newDiff, diff);
        i++;
        j++;
    }
    return diff;
}

const rebuild = (root: TreeNode | null): number[] => {
    if (!root) return [];
    return [...rebuild(root.left), root?.val, ...rebuild(root.right)];
};
// @lc code=end
